'''
Created on May 2, 2011

@author: oabalbin
'''



def build_concesus_table(pm, cm, dumped_files,ofile, mmapfile, 
                         complement, act_snps=None, dbsnp=None, hapmap=None, validated=None):
    '''
    '''
    fields, format, names=fields_table()
    ncol = len(fields)
    nrow = len(pm)
    # Functional Annotation: Majority Vote and Present or not in HapMap
    
    print >> sys.stderr, "Building concensus table ...."
    
    if act_snps is not None and dbsnp is not None and hapmap is not None and validated is not None:
        annot = ['Majority','dbSNP','HapMap', 'Actionable', 'Validated']
        mcol, dcol, hcol, acol, vcol = -5, -4,-3,-2,-1
            
    elif act_snps is not None and dbsnp is not None and hapmap is not None:
        annot = ['Majority','dbSNP','HapMap', 'Actionable']
        mcol, dcol, hcol, acol = -4,-3,-2,-1
        
    elif act_snps is not None and validated is not None and hapmap is not None:
        annot = ['Majority','HapMap', 'Actionable', 'Validated']
        mcol, hcol, acol, vcol = -4,-3,-2,-1
        
    elif dbsnp is not None and hapmap is not None:
        annot = ['Majority','dbSNP','HapMap']
        mcol, dcol, hcol = -3,-2,-1
        
    elif dbsnp is not None and act_snps is not None:
        annot = ['Majority','dbSNP','Actionable']
        mcol, dcol, acol = -3,-2,-1

    elif hapmap is not None and act_snps is not None:
        annot = ['Majority','HapMap','Actionable']
        mcol, hcol, acol = -3,-2,-1
        
    elif act_snps is not None and validated is not None:
        annot = ['Majority','Actionable', 'Validated']
        mcol, acol, vcol = -3,-2,-1

    else:
        annot = ['Majority']
        mcol=-1

        
    ############## Function
    #newpm=defaultdict()
    imat = np.zeros( (nrow,len(dumped_files)+len(annot) ) ) 
    #act_gen_names = np.empty( nrow, dtype='str')
    act_gen_names=defaultdict()
    #[act_gen_names.append('nan') for i in range(nrow)]
    
    # file1, file2, file3, file n.  
    
    
    for k, df in enumerate(dumped_files):
        ovcf=VCF()
        ovcf.readFromPickle(df)
        # create a matrix for this file
        cmat = np.empty( (nrow,ncol) )
        
        for coord, i in pm.iteritems():
            snv_list = ovcf[[coord]] # list of 1 snv 
            if not snv_list:
                cmat[i,:] = np.nan
                #print >> sys.stderr, "Not snps for this coordinate %s"%(coord)
            else:
                # Intersection matrix
                imat[i,k]=1

                for snv in snv_list:
                    # Filling annotation matrix
                    #print snv
                    loc = snv['COORD']
                    #newpm[loc]=i
                    if len(snv_list) > 1: 
                        print >> sys.stderr, "There is more than one snp with the same location"
                    
                    if act_snps is not None:
                        if loc in act_snps.keys():
                            
                            imat[i,acol] = 1
                            #act_gen_names[i]=act_snps[loc]
                            #act_gen_names.insert(i,act_snps[loc])
                            act_gen_names[i]=act_snps[loc]
                            
                        else:
                            imat[i,acol] = 0
                            if 'NON_SYNONYMOUS_CODING(SPLICE_SITE)' in snv.keys():
                                gen_name=snv['NON_SYNONYMOUS_CODING(SPLICE_SITE)']
                            elif 'NON_SYNONYMOUS_CODING' in snv.keys():
                                gen_name=snv['NON_SYNONYMOUS_CODING']
                            else:
                                gen_name='NAN'
                                
                            act_gen_names[i]='NotAct'+'_'+gen_name
                            
                                                
                    if  dbsnp is not None:
                        imat[i,dcol] = 1 if loc in dbsnp else 0
                    if hapmap is not None:
                        imat[i,hcol] = 1 if loc in hapmap else 0
                    if validated is not None:
                        imat[i,vcol] = 1 if loc in validated else 0
                    
                    # Properties of the snp
                    for prop,j in fields.iteritems():
                        
                        try:
                            cmat[i,j] = snv[prop]
                        except KeyError:
                            print >> sys.stderr, "%s, Error with this snv %s, it is missing field %s"%(df,coord,prop)
                            if prop=="SB":
                                # This number means the field was not present in the vcf
                                cmat[i,j]=999
                            else:
                                cmat[i,j] = np.nan
                            
     
        # concatenate matrix for this file to gral matrix
        if k==0:
            Cmat=np.copy(cmat)
        else:
            Cmat = np.hstack( (Cmat,cmat) )
            
    # Get the majority vote for the snv calls
    fformat=[]
    fnames=[]
    fmethods=[]
    for i in range(len(dumped_files)):
        tn = ['M%d_%s'%(i,n) for n in names]
        fformat+=format
        fnames+=tn
        fmethods.append('M%d'%(i)) 
    
    fmethods=fmethods+annot
    fmethods.reverse()
    [fformat.insert(0,'%d') for i in range(imat.shape[1])]
    [fnames.insert(0,f) for f in fmethods]
    
    imat[:,mcol]=np.sum(imat[:,:mcol], axis=1)
    Cmat = np.hstack( (imat,Cmat) )
    write_table(Cmat,ofile,",".join(fformat),mmapfile, pm, fnames, act_gen_names)
    
    return fnames
